populateVariantFromExcel
- ๐ฌ๐ง English
- ๐ฎ๐น Italian
Function Name: populateVariantFromExcel
Author: Domenico Cerone Creation Date: 25/09/2025
Last Reviewer: Domenico Cerone
Trigger: HTTPS (onRequest)
Purpose: Complete workflow for automatic product data population from JSON arrays. Handles the entire process: JSON parsing โ image download from URLs โ direct mapping โ storage with public URLs. Processes products from JSON payload and creates/updates both Products and Variants collections. Note: EAN/UPC codes are stored at variant level only, not at product level.
Detailed Functionalityโ
This Firebase Function performs a comprehensive 7-step workflow for processing JSON product arrays with dynamic batch processing optimized for volumes from 5 to 500+ products.
1. JSON RECEPTION AND VALIDATIONโ
- Receives JSON array directly in request body (Content-Type: application/json)
- Validates format and content of the array
- Direct parsing of product objects
- Each object represents a product/variant
- Validates required fields (skuCode, brand) for each product
2. DYNAMIC PARALLEL BATCH PROCESSING WITH MUTEX SYNCHRONIZATIONโ
Dynamic batch configuration based on product volume:
- โค50 products: 10-element batches + 300ms pauses (fast mode)
- 51-200 products: 15-element batches + 500ms pauses (balanced mode)
-
200 products: 20-element batches + 800ms pauses (robust mode)
Processing Features:
- Sequential batch processing for optimal performance
- Parallel processing within each batch for maximum efficiency
- NEW: Mutex synchronization to prevent duplicate product creation
โ When 2+ variants of the same GlassesName are in the same batch
โ Exclusive lock system to serialize Products collection creation
โ Polling with backoff to wait for lock release (100ms โ 2000ms max)
โ Automatic cleanup of expired locks to prevent memory leaks
โ Thread-safe tag creation using
findOrCreateTagThreadSafe()from tagUtils.js โ Prevents duplicate Tags documents in high-concurrency scenarios - Intelligent dynamic pauses between batches for system stability
- Detailed progress logging with memory monitoring for large arrays >200 products
- Individual product and batch error handling without blocking others
- Separate operation tracking for each product
- Optimized for handling up to 500+ products without timeout (60 minutes maximum)
- Automatic modes: Standard, Optimized, Ultra-Robust
3. IMAGE DOWNLOAD FROM URLsโ
Image Processing Details:
- Extracts URLs from fields img_name_001, img_name_002, etc. (up to img_name_020)
- Parallel download of images from direct URLs
- Automatic retry system: 3 attempts with progressive delay (100ms โ 300ms โ 600ms)
- Robust HTTP error handling (404, 500, timeout, network errors)
- Content-type validation for image files
- Firebase Storage upload with UUID token for public URLs
- Same folder structure as populateVariantFromSku:
ARS_Library_Product_Data/{skuCode}/thumbnail/ - File naming convention:
{modelCode}_{frameColor}_{lensColor}_{detail}.jpg - Guaranteed cleanup and error recovery
- Caching optimization: checks if images already exist
4. DIRECT MAPPING (WITHOUT SAP METADATA)โ
Mapping Features:
- Direct mapping from JSON fields to Firestore collections
- No external API calls required
- Data validation and type conversion
- Special field handling (boolean, date, arrays)
- Brand normalization according to business rules
- Tag creation for categorization fields
5. DOCUMENT CREATION AND MAPPINGโ
Dynamic document creation system:
- Create Variants document FIRST (to get the ID)
- Create/update Products document with variant ID
- Update Variants document with productRef
- Batch management from JSON data
- Create/update document in Products collection (without catalogOrdersRef, no EAN/UPC codes stored here)
- Create/update document in Variants collection (batch from JSON, EAN/UPC codes stored here)
Related Components:
- createProductDocument - Handles Products collection management with thread-safe tag creation
- createVariantDocument - Handles Variants collection management with brand normalization
- tagUtils - Provides thread-safe tag creation utilities with mutex synchronization to prevent duplicates
Brand Normalization Systemโ
The function includes an intelligent brand normalization system that applies business rules to standardize brand names from JSON data to consistent marketing brand names.
Brand Mapping Rules:
- Hugo brands: "HUGO" โ "HUGO EYEWEAR"
- Boss brands: "HUGO BOSS", "BOSS ORANGE" โ "BOSS EYEWEAR"
- Carrera brands: "CARRERA BY JIMMYCHOO", "CARRERA BIKE", "CARRERA SNOW", "CARRERA DUCATI" โ "CARRERA"
- Polaroid brands: "POLAROID ANCILLARIES", "POLAROID KIDS", "POLAROID STAYSAFE" โ "POLAROID"
- Smith brands: "SMITH FASHION & ACC.", "SMITH BIKE HELMETS", "SMITH SNOW", "SMITH BIKE GOGGLES", "PRIVATE LABEL SMITH", "SUNCLOUD" โ "SMITH OPTICS"
- Other brands: Remain unchanged
Implementation: The mapToNormalizedBrand() function is called automatically during data mapping to ensure consistent brand naming across both Products and Variants collections.
Benefits:
- Consistent brand representation across all collections
- Simplified brand management and filtering
- Alignment with marketing brand guidelines
- Automatic application without manual intervention
Mutex Synchronization Systemโ
Problem Solved: When multiple variants of the same product (same GlassesName) are processed in parallel within the same batch, they could attempt to create the same Products document simultaneously, leading to race conditions and potential duplicates.
Solution: Exclusive lock system using Map-based mutex:
- Lock Acquisition: Before creating/updating a Products document, the function acquires an exclusive lock using the GlassesName as key
- Lock Key Format:
PRODUCT_CREATE_{GlassesName} - Polling Mechanism: If a lock is already held, the function waits with exponential backoff (100ms โ 2000ms max)
- Automatic Cleanup: Expired locks (older than 10 minutes) are automatically cleaned up to prevent memory leaks
- Granular Locking: Each GlassesName has its own lock, so different products can be processed simultaneously
- Error Safety: Locks are released in finally blocks to ensure cleanup even on errors
Benefits:
- Prevents duplicate Products documents
- Maintains data consistency in high-concurrency scenarios
- Optimizes performance by allowing parallel processing of different products
- Provides automatic recovery from stuck locks
6. RESULT AGGREGATIONโ
- Collection of results from all processed products
- Success and error counting
- Detailed logging for debugging
- Performance metrics and timing
7. FINAL RESPONSEโ
- JSON response with detailed results
- List of processed products with success/error status
- General processing statistics
- API call tracking and image download statistics
JSON Field Mappingโ
Identification Fieldsโ
- skuCode โ Variants.skuModel (unique variant identifier)
- EAN โ Variants.eanCode (EAN code - NOT stored in Products)
- UPC โ Variants.upcCode (UPC code - NOT stored in Products)
- GTIN โ [IGNORED] (not used)
- GlassesName โ Products.modelName + Variants.glassesName (model name)
Brand and Organizationโ
- brand โ Products.mainBrandRef + Variants.mainBrandRef (MainBrands collection ID with normalization)
- Batch โ Variants.batch (production batch)
- Priority โ [IGNORED] (not used)
- Line โ Products.nomeLinea + Products.list_line_tags[] (line + tag ID)
Colors and Designโ
- frameColor โ Variants.frameColor + Variants.list_size_color_tags[0] (color + tag ID)
- lensColor โ Variants.lensesColor (lens color)
Dimensionsโ
- size โ Variants.size.size + Variants.list_size_color_tags[1] (size + tag ID)
- bridge โ Variants.size.bridge (bridge)
- lensHeight โ Variants.size.lensHeight (lens height)
- templeLenght โ Variants.size.templeLength (temple length)
- baseCurve โ Variants.size.baseCurve (base curve)
Product Categorization (all create automatic tags)โ
- typology โ Products.catType + Products.list_tags[] (Sunglasses/Optical + tag ID)
- gender โ Products.catGender + Products.list_tags[] (gender + tag ID)
- shape โ Products.catForma + Products.list_tags[] (shape + tag ID)
- materials โ Products.catMaterialOne + Products.list_tags[] (material + tag ID)
- polarized โ Products.polarised + Products.list_tags[] (polarization + tag ID)
- lensTreatment โ Products.catLensesTreat + Products.list_tags[] (treatment + tag ID)
- hingeType โ Products.hingeType + Products.list_tags[] (hinge + tag ID)
Descriptionsโ
- descriptionEN โ Products.descriptionEn (English description)
- descriptionIT โ Products.descriptionIt (Italian description)
- url_product โ Products.url_product (product URL)
Images (automatic download from URLs)โ
- img_name_001 โ Products.poster + Products.imgUrl + Variants.poster (view 00)
- img_name_002 โ Variants.poster4 (view 01)
- img_name_003 โ Variants.poster3 (view 02)
- img_name_004 โ Variants.list_images[3] (view 03)
- img_name_005-020 โ Variants.list_images[4-19] (additional views)
- img_name_008 โ Variants.poster2 (view 07)
- IMG_Assets_Status โ [IGNORED] (not used)
Input (Payload)โ
Method: POST
Headers:
Content-Type: application/json(required)
Body: JSON array of products
[
{
"skuCode": "SMITH001ARV01",
"Batch": "R1_2025",
"Priority": "High",
"UPC": 716736839554,
"EAN": 716736839554,
"GTIN": 716736839554,
"GlassesName": "Smith Arvo Sunglasses",
"frameColor": "Matte Dark Tortoise",
"lensColor": "ChromaPop Polarized Bronze Mirror",
"lensHeight": 42,
"bridge": 16,
"templeLenght": 125,
"baseCurve": "8 BASE",
"size": "Medium",
"Line": "Arvo Collection",
"brand": "SMITH",
"typology": "Sunglasses",
"gender": "Unisex",
"shape": "Rectangle",
"materials": "Plastic",
"polarized": "Yes",
"lensTreatment": "ChromaPop",
"hingeType": "Standard",
"url_product": "https://example.com/smith-arvo",
"descriptionIT": "Gli occhiali da sole quotidiani perfetti per ogni occasione",
"descriptionEN": "The daily driver. The Smith Arvo sunglasses are that everyday pair of sunglasses made for living the good life.",
"img_name_001": "https://example.com/arvo-tortoise-001.jpg",
"img_name_002": "https://example.com/arvo-tortoise-002.jpg",
"img_name_003": "https://example.com/arvo-tortoise-003.jpg",
"img_name_004": "https://example.com/arvo-tortoise-004.jpg",
"IMG_Assets_Status": "OK"
}
]
Required Fields:
skuCode(string): Unique SKU identifierbrand(string): Brand name (will be normalized)
Output (Success)โ
{
"success": true,
"source": "JSON Array",
"totalProducts": 2,
"successCount": 2,
"errorCount": 0,
"processedProducts": [
{
"success": true,
"skuCode": "SMITH001ARV01",
"eanCode": "716736839554",
"upcCode": "716736839554",
"productRef": "auto_generated_product_id",
"variantRef": "auto_generated_variant_id",
"productOperation": "create",
"variantOperation": "create",
"message": "Prodotto SMITH001ARV01 processato con successo da JSON",
"apiCalls": {
"JSON Product": "SMITH001ARV01",
"Images Downloaded": "4/4",
"First Image URL": "https://example.com/arvo-tortoise-001.jpg"
}
}
],
"message": "Processing JSON completato: 2/2 prodotti processati con successo",
"recap": "parsing array JSON โ 2 prodotti estratti โ 2 prodotti processati con successo โ 0 prodotti con errori",
"allApiCalls": {
"Product_1_SMITH001ARV01": { ... },
"Product_2_SMITH001ARV02": { ... }
},
"jsonInfo": {
"totalItems": 2,
"source": "JSON_DIRECT",
"processingTime": "1234ms"
}
}
Technical Specificationsโ
Firebase Function Configuration:
- Timeout: 3600 seconds (60 minutes) - maximum for HTTP Functions v2
- Memory: 1GiB - optimized for JSON processing and image downloads
- Region: europe-central2 - optimal performance for Europe
- CORS: Enabled for frontend calls
Performance Guarantees by Volume:
- 5-50 products: 30 seconds - 3 minutes (standard mode)
- 51-200 products: 4-15 minutes (optimized mode)
- 201-500 products: 20-45 minutes (ultra-robust mode)
- No timeout guaranteed up to 500 products
Testingโ
URL (if HTTPS): http://127.0.0.1:5001/arshadesstaging/europe-central2/populateVariantFromExcel
Test with Emulator:
- Start Firebase emulator:
firebase emulators:start --only functions - Ensure you're using Node.js version 20:
nvm use 20 - Test with curl:
curl -X POST "http://127.0.0.1:5001/arshadesstaging/europe-central2/populateVariantFromExcel" \
-H "Content-Type: application/json" \
-d '[
{
"skuCode": "TEST001",
"brand": "SMITH",
"GlassesName": "Test Sunglasses",
"frameColor": "Black",
"lensColor": "Gray",
"size": "Medium",
"typology": "Sunglasses",
"gender": "Unisex",
"img_name_001": "https://example.com/test-001.jpg"
}
]'
Postman Testing:
- Method: POST
- URL:
http://127.0.0.1:5001/arshadesstaging/europe-central2/populateVariantFromExcel - Headers:
- Key:
Content-Type - Value:
application/json
- Key:
- Body: raw JSON (see examples above)
Deploy Commandโ
firebase deploy --only functions:populateVariantFromExcel
Production URLโ
Live Function: Not yet deployed to production
Function Name: populateVariantFromExcel
Autore: Domenico Cerone Data di creazione: 25/09/2025
Last Reviewer: Domenico Cerone
Trigger: HTTPS (onRequest)
Purpose: Workflow completo per il popolamento automatico dei dati prodotto da array JSON. Gestisce l'intero processo: parsing JSON โ download immagini da URL โ mapping diretto โ storage con URL pubblici. Processa prodotti da payload JSON e crea/aggiorna sia le collezioni Products che Variants. Nota: I codici EAN/UPC sono memorizzati solo a livello di variante, non a livello di prodotto.
Funzionamento Dettagliatoโ
Questa Firebase Function esegue un workflow completo di 7 step per il processing di array JSON di prodotti con batch processing dinamico ottimizzato per volumi da 5 a 500+ prodotti.
1. RICEZIONE E VALIDAZIONE JSONโ
- Riceve array JSON direttamente nel body della richiesta (Content-Type: application/json)
- Valida formato e contenuto dell'array
- Parsing diretto degli oggetti prodotto
- Ogni oggetto rappresenta un prodotto/variante
- Valida campi obbligatori (skuCode, brand) per ogni prodotto
2. PROCESSING BATCH PARALLELO DINAMICO CON MUTEX SINCRONIZZAZIONEโ
Configurazione batch dinamica basata sul volume di prodotti:
- โค50 prodotti: batch da 10 elementi + pause 300ms (modalitร veloce)
- 51-200 prodotti: batch da 15 elementi + pause 500ms (modalitร bilanciata)
-
200 prodotti: batch da 20 elementi + pause 800ms (modalitร robusta)
Caratteristiche Processing:
- Processing batch sequenziale per prestazioni ottimali
- Processing parallelo all'interno di ogni batch per massima efficienza
- NUOVO: Mutex sincronizzazione per evitare creazione prodotti duplicati
โ Quando 2+ varianti dello stesso GlassesName sono nello stesso batch
โ Sistema di lock esclusivo per serializzare la creazione di Products
โ Polling con backoff per attendere rilascio lock (100ms โ 2000ms max)
โ Cleanup automatico lock scaduti per evitare memory leak
โ Creazione tag thread-safe usando
findOrCreateTagThreadSafe()da tagUtils.js โ Previene documenti Tags duplicati in scenari di alta concorrenza - Pause intelligenti dinamiche tra batch per stabilitร del sistema
- Logging dettagliato del progresso con monitoraggio memoria per array grandi >200 prodotti
- Gestione errori per singolo prodotto e per batch senza bloccare gli altri
- Tracking operazioni separate per ogni prodotto
- Ottimizzato per gestire fino a 500+ prodotti senza timeout (60 minuti massimo)
- Modalitร automatiche: Standard, Ottimizzata, Ultra-Robusta
3. DOWNLOAD IMMAGINI DA URLโ
Dettagli Processing Immagini:
- Estrae URL dai campi img_name_001, img_name_002, ecc. (fino a img_name_020)
- Download parallelo delle immagini da URL diretti
- Sistema di retry automatico: 3 tentativi con delay progressivo (100ms โ 300ms โ 600ms)
- Gestione errori HTTP robusta (404, 500, timeout, network errors)
- Validazione content-type per file immagine
- Upload su Firebase Storage con token UUID per URL pubblici
- Stessa struttura cartelle di populateVariantFromSku:
ARS_Library_Product_Data/{skuCode}/thumbnail/ - Convenzione nomi file:
{modelCode}_{frameColor}_{lensColor}_{detail}.jpg - Cleanup garantito e recovery degli errori
- Ottimizzazione caching: controlla se le immagini esistono giร
4. MAPPING DIRETTO (SENZA METADATA SAP)โ
Caratteristiche Mapping:
- Mapping diretto dai campi JSON alle collezioni Firestore
- Nessuna chiamata API esterna richiesta
- Validazione dati e conversione tipi
- Gestione campi speciali (boolean, date, arrays)
- Normalizzazione brand secondo regole di business
- Creazione tag per campi di categorizzazione
5. CREAZIONE DOCUMENTI E MAPPINGโ
Sistema creazione documenti dinamico:
- Crea documento Variants PRIMA (per ottenere l'ID)
- Crea/aggiorna documento Products con ID della variante
- Aggiorna documento Variants con productRef
- Gestione batch dai dati JSON
- Creazione/aggiornamento documento nella collezione Products (senza catalogOrdersRef, nessun codice EAN/UPC memorizzato qui)
- Creazione/aggiornamento documento nella collezione Variants (batch da JSON, codici EAN/UPC memorizzati qui)
Componenti Correlati:
- createProductDocument - Gestisce la collezione Products con creazione tag thread-safe
- createVariantDocument - Gestisce la collezione Variants con normalizzazione brand
- tagUtils - Fornisce utilitร per creazione tag thread-safe con sincronizzazione mutex per prevenire duplicati
Sistema Normalizzazione Brandโ
La funzione include un sistema intelligente di normalizzazione brand che applica regole di business per standardizzare i nomi brand dai dati JSON ai nomi brand marketing consistenti.
Regole Mappatura Brand:
- Brand Hugo: "HUGO" โ "HUGO EYEWEAR"
- Brand Boss: "HUGO BOSS", "BOSS ORANGE" โ "BOSS EYEWEAR"
- Brand Carrera: "CARRERA BY JIMMYCHOO", "CARRERA BIKE", "CARRERA SNOW", "CARRERA DUCATI" โ "CARRERA"
- Brand Polaroid: "POLAROID ANCILLARIES", "POLAROID KIDS", "POLAROID STAYSAFE" โ "POLAROID"
- Brand Smith: "SMITH FASHION & ACC.", "SMITH BIKE HELMETS", "SMITH SNOW", "SMITH BIKE GOGGLES", "PRIVATE LABEL SMITH", "SUNCLOUD" โ "SMITH OPTICS"
- Altri brand: Rimangono invariati
Implementazione: La funzione mapToNormalizedBrand() viene chiamata automaticamente durante il mapping dati per garantire nomenclatura brand consistente in entrambe le collezioni Products e Variants.
Vantaggi:
- Rappresentazione brand consistente in tutte le collezioni
- Gestione e filtraggio brand semplificato
- Allineamento con le linee guida brand marketing
- Applicazione automatica senza intervento manuale
Sistema Mutex Sincronizzazioneโ
Problema Risolto: Quando piรน varianti dello stesso prodotto (stesso GlassesName) vengono processate in parallelo nello stesso batch, potrebbero tentare di creare lo stesso documento Products simultaneamente, causando race condition e potenziali duplicati.
Soluzione: Sistema di lock esclusivo usando mutex basato su Map:
- Acquisizione Lock: Prima di creare/aggiornare un documento Products, la funzione acquisisce un lock esclusivo usando il GlassesName come chiave
- Formato Chiave Lock:
PRODUCT_CREATE_{GlassesName} - Meccanismo Polling: Se un lock รจ giร detenuto, la funzione attende con backoff esponenziale (100ms โ 2000ms max)
- Cleanup Automatico: Lock scaduti (piรน vecchi di 10 minuti) vengono automaticamente puliti per evitare memory leak
- Locking Granulare: Ogni GlassesName ha il suo lock, cosรฌ prodotti diversi possono essere processati simultaneamente
- Sicurezza Errori: I lock vengono rilasciati nei blocchi finally per garantire cleanup anche in caso di errori
Vantaggi:
- Previene documenti Products duplicati
- Mantiene consistenza dati in scenari alta concorrenza
- Ottimizza performance permettendo processing parallelo di prodotti diversi
- Fornisce recovery automatico da lock bloccati
6. AGGREGAZIONE RISULTATIโ
- Raccolta risultati di tutti i prodotti processati
- Conteggio successi ed errori
- Logging dettagliato per debugging
- Metriche performance e timing
7. RESPONSE FINALEโ
- Response JSON con risultati dettagliati
- Lista prodotti processati con stato successo/errore
- Statistiche generali del processing
- Tracking chiamate API e statistiche download immagini
Mappatura Campi JSONโ
Campi Identificativiโ
- skuCode โ Variants.skuModel (identificatore univoco variante)
- EAN โ Variants.eanCode (codice EAN - NON memorizzato in Products)
- UPC โ Variants.upcCode (codice UPC - NON memorizzato in Products)
- GTIN โ [IGNORATO] (non utilizzato)
- GlassesName โ Products.modelName + Variants.glassesName (nome modello)
Brand e Organizzazioneโ
- brand โ Products.mainBrandRef + Variants.mainBrandRef (ID collezione MainBrands con normalizzazione)
- Batch โ Variants.batch (lotto produzione)
- Priority โ [IGNORATO] (non utilizzato)
- Line โ Products.nomeLinea + Products.list_line_tags[] (linea + ID tag)
Colori e Designโ
- frameColor โ Variants.frameColor + Variants.list_size_color_tags[0] (colore + ID tag)
- lensColor โ Variants.lensesColor (colore lenti)
Dimensioniโ
- size โ Variants.size.size + Variants.list_size_color_tags[1] (taglia + ID tag)
- bridge โ Variants.size.bridge (ponte)
- lensHeight โ Variants.size.lensHeight (altezza lente)
- templeLenght โ Variants.size.templeLength (lunghezza aste)
- baseCurve โ Variants.size.baseCurve (curvatura base)
Categorizzazione Prodotto (tutti creano tag automatici)โ
- typology โ Products.catType + Products.list_tags[] (Sunglasses/Optical + ID tag)
- gender โ Products.catGender + Products.list_tags[] (genere + ID tag)
- shape โ Products.catForma + Products.list_tags[] (forma + ID tag)
- materials โ Products.catMaterialOne + Products.list_tags[] (materiale + ID tag)
- polarized โ Products.polarised + Products.list_tags[] (polarizzazione + ID tag)
- lensTreatment โ Products.catLensesTreat + Products.list_tags[] (trattamento + ID tag)
- hingeType โ Products.hingeType + Products.list_tags[] (cerniera + ID tag)
Descrizioniโ
- descriptionEN โ Products.descriptionEn (descrizione inglese)
- descriptionIT โ Products.descriptionIt (descrizione italiana)
- url_product โ Products.url_product (URL prodotto)
Immagini (download automatico da URL)โ
- img_name_001 โ Products.poster + Products.imgUrl + Variants.poster (vista 00)
- img_name_002 โ Variants.poster4 (vista 01)
- img_name_003 โ Variants.poster3 (vista 02)
- img_name_004 โ Variants.list_images[3] (vista 03)
- img_name_005-020 โ Variants.list_images[4-19] (viste aggiuntive)
- img_name_008 โ Variants.poster2 (vista 07)
- IMG_Assets_Status โ [IGNORATO] (non utilizzato)
Input (Payload)โ
Metodo: POST
Headers:
Content-Type: application/json(richiesto)
Body: Array JSON di prodotti
[
{
"skuCode": "SMITH001ARV01",
"Batch": "R1_2025",
"Priority": "High",
"UPC": 716736839554,
"EAN": 716736839554,
"GTIN": 716736839554,
"GlassesName": "Smith Arvo Sunglasses",
"frameColor": "Matte Dark Tortoise",
"lensColor": "ChromaPop Polarized Bronze Mirror",
"lensHeight": 42,
"bridge": 16,
"templeLenght": 125,
"baseCurve": "8 BASE",
"size": "Medium",
"Line": "Arvo Collection",
"brand": "SMITH",
"typology": "Sunglasses",
"gender": "Unisex",
"shape": "Rectangle",
"materials": "Plastic",
"polarized": "Yes",
"lensTreatment": "ChromaPop",
"hingeType": "Standard",
"url_product": "https://example.com/smith-arvo",
"descriptionIT": "Gli occhiali da sole quotidiani perfetti per ogni occasione",
"descriptionEN": "Il driver quotidiano. Gli occhiali da sole Smith Arvo sono quella coppia quotidiana di occhiali da sole fatti per vivere la bella vita.",
"img_name_001": "https://example.com/arvo-tortoise-001.jpg",
"img_name_002": "https://example.com/arvo-tortoise-002.jpg",
"img_name_003": "https://example.com/arvo-tortoise-003.jpg",
"img_name_004": "https://example.com/arvo-tortoise-004.jpg",
"IMG_Assets_Status": "OK"
}
]
Campi Obbligatori:
skuCode(string): Identificatore SKU univocobrand(string): Nome brand (verrร normalizzato)
Output (Successo)โ
{
"success": true,
"source": "JSON Array",
"totalProducts": 2,
"successCount": 2,
"errorCount": 0,
"processedProducts": [
{
"success": true,
"skuCode": "SMITH001ARV01",
"eanCode": "716736839554",
"upcCode": "716736839554",
"productRef": "auto_generated_product_id",
"variantRef": "auto_generated_variant_id",
"productOperation": "create",
"variantOperation": "create",
"message": "Prodotto SMITH001ARV01 processato con successo da JSON",
"apiCalls": {
"JSON Product": "SMITH001ARV01",
"Images Downloaded": "4/4",
"First Image URL": "https://example.com/arvo-tortoise-001.jpg"
}
}
],
"message": "Processing JSON completato: 2/2 prodotti processati con successo",
"recap": "parsing array JSON โ 2 prodotti estratti โ 2 prodotti processati con successo โ 0 prodotti con errori",
"allApiCalls": {
"Product_1_SMITH001ARV01": { ... },
"Product_2_SMITH001ARV02": { ... }
},
"jsonInfo": {
"totalItems": 2,
"source": "JSON_DIRECT",
"processingTime": "1234ms"
}
}
Specifiche Tecnicheโ
Configurazione Firebase Function:
- Timeout: 3600 secondi (60 minuti) - massimo per HTTP Functions v2
- Memoria: 1GiB - ottimizzata per processing JSON e download immagini
- Regione: europe-central2 - performance ottimali per Europa
- CORS: Abilitato per chiamate da frontend
Prestazioni Garantite per Volume:
- 5-50 prodotti: 30 secondi - 3 minuti (modalitร standard)
- 51-200 prodotti: 4-15 minuti (modalitร ottimizzata)
- 201-500 prodotti: 20-45 minuti (modalitร ultra-robusta)
- Nessun timeout garantito fino a 500 prodotti
Testingโ
URL (if HTTPS): http://127.0.0.1:5001/arshadesstaging/europe-central2/populateVariantFromExcel
Test con Emulator:
- Avviare l'emulatore Firebase:
firebase emulators:start --only functions - Assicurarsi di usare Node.js versione 20:
nvm use 20 - Testare con curl:
curl -X POST "http://127.0.0.1:5001/arshadesstaging/europe-central2/populateVariantFromExcel" \
-H "Content-Type: application/json" \
-d '[
{
"skuCode": "TEST001",
"brand": "SMITH",
"GlassesName": "Test Sunglasses",
"frameColor": "Black",
"lensColor": "Gray",
"size": "Medium",
"typology": "Sunglasses",
"gender": "Unisex",
"img_name_001": "https://example.com/test-001.jpg"
}
]'
Test con Postman:
- Metodo: POST
- URL:
http://127.0.0.1:5001/arshadesstaging/europe-central2/populateVariantFromExcel - Headers:
- Key:
Content-Type - Value:
application/json
- Key:
- Body: raw JSON (vedi esempi sopra)
Deploy Commandโ
firebase deploy --only functions:populateVariantFromExcel
URL di Produzioneโ
Funzione Live: Non ancora deployata in produzione